package com.bac.bacplatform;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.bac.javabeans.FuellingCard;
import com.bac.javabeans.Page;
import com.bac.utils.Config;
import com.bac.utils.Storage;
import com.bac.utils.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.R.integer;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout.LayoutParams;

public class KeyToOilActivity extends BaseActivity implements OnClickListener {
	private AutoCompleteTextView cardNum;
	private ArrayAdapter<String> mAdapter;
	private EditText money_text;
	private TextView totalTextView, totalTextView2, discountTextView,
			ensurepayteTextView, ensurepayteTextView2, monthNum;
	private RelativeLayout rl_addNum, rl_subNum, month_number;
	private PopupWindow mPopupWindow;
	private Button btn_goRecharge;

	private Boolean isBoolean;

	private int mCurrentCard = 0;
	// 是否直充
	private Boolean mIsRecharge = true;

	// 卡号数据
	private ArrayList<String> mCardStrings = new ArrayList<String>();
	private ArrayList<String> mCardNameString = new ArrayList<String>();
	
	private int payMethod;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.key_oil);
		isBoolean = true;
		payMethod = getIntent().getIntExtra("paymethod", 2);

		cardNum = (AutoCompleteTextView) findViewById(R.id.card_number);
		mAdapter = new ArrayAdapter<String>(this, R.layout.drop_down_item,
				R.id.tv_content, mCardNameString);

		cardNum.setAdapter(mAdapter);

		cardNum.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				cardNum.showDropDown();
			}
		});

		findViewById(R.id.todown).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i("dropdown image", "click drop down");
				cardNum.showDropDown();
			}
		});

		 cardNum.setOnItemClickListener(new OnItemClickListener() {
		
		 @Override
		 public void onItemClick(AdapterView<?> parent, View view,
		 int position, long id) {
		 String currentCard = mCardNameString.get(position);
		 String[] strArray = currentCard.split(" ");
		 cardNum.setText(strArray[0]);
		 Log.i("item clicked---", strArray[0]);
		
		 InputMethodManager imm = (InputMethodManager)
		 getSystemService(Context.INPUT_METHOD_SERVICE);
		 imm.hideSoftInputFromWindow(cardNum.getWindowToken(), 0);
		 }
		 });
		getHistoryCards();
		// String username = Storage.getString(getApplicationContext(),
		// Config.USER_ACCOUNT_KEY);
		// if (username.length() != 0) {
		// String localCard = Storage.getString(getApplicationContext(),
		// username);
		// if (localCard.length() != 0) {
		// cardNum.setText(localCard);
		// }
		//
		// }
	}

	@Override
	public void init() {
		money_text = (EditText) findViewById(R.id.money_text);
		totalTextView = (TextView) findViewById(R.id.text02);
		totalTextView2 = (TextView) findViewById(R.id.rl_tv02);
		discountTextView = (TextView) findViewById(R.id.discount_tv01);
		ensurepayteTextView = (TextView) findViewById(R.id.pay_text3);
		ensurepayteTextView2 = (TextView) findViewById(R.id.rl_04_tv02);
		monthNum = (TextView) findViewById(R.id.month_number_tv2);

		String singleYieldString = Storage.getString(getApplicationContext(),
				"SingleYield");
		singleYieldString = singleYieldString.equals("") ? "0.00"
				: singleYieldString;
		String yieldString = Storage
				.getString(getApplicationContext(), "Yield");
		yieldString = yieldString.equals("") ? "0.00" : yieldString;
		TextView discount2 = (TextView) findViewById(R.id.discount_tv02);

		discountTextView.setText(""
				+ (int) (Double.parseDouble(singleYieldString) * 100));
		discount2.setText("" + (int) (Double.parseDouble(yieldString) * 100));

		rl_addNum = (RelativeLayout) findViewById(R.id.additive);
		rl_addNum.setOnClickListener(this);
		rl_subNum = (RelativeLayout) findViewById(R.id.subtraction);
		rl_subNum.setOnClickListener(this);
		month_number = (RelativeLayout) findViewById(R.id.month_number);
		month_number.setOnClickListener(this);

		btn_goRecharge = (Button) findViewById(R.id.go_recharge);
		btn_goRecharge.setOnClickListener(this);

		findViewById(R.id.go_recharge_two).setOnClickListener(this);
		findViewById(R.id.agree_it).setOnClickListener(this);
		findViewById(R.id.lay_agree).setOnClickListener(this);

		findViewById(R.id.title_left).setOnClickListener(this);

		findViewById(R.id.toleft).setOnClickListener(this);
		findViewById(R.id.toright).setOnClickListener(this);
	}

	/**
	 * {"pageSize":10,"pageNo":1,"totalPages":1,"totalCount":2,"list":[{"id":2,
	 * "cardNo"
	 * :"123456987","cardOwner":"小黑"},{"id":1,"cardNo":"123456789","cardOwner"
	 * :"小红"}]} <br>
	 * 获取历史充值卡信息
	 */
	public void getHistoryCards() {
		Listener<String> sListener = new Listener<String>() {
			@SuppressWarnings("rawtypes")
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("getcards----success", response.toString());
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<Page>() {
				}.getType();
				Page page = gson.fromJson(response, type);
				@SuppressWarnings("unchecked")
				List<FuellingCard> cards = page.getList();
				for (int i = 0; i < cards.size(); i++) {
					// 卡号后面加上名字
					mCardNameString.add(cards.get(i).getCardNo() + " "
							+ cards.get(i).getCardOwner());
					// 卡号添加到数组，方便后续校验
					mCardStrings.add(cards.get(i).getCardNo());
				}
				mAdapter.notifyDataSetChanged();
				String username = Storage.getString(getApplicationContext(),
						Config.USER_ACCOUNT_KEY);
				if (username.length() != 0) {
					String localCard = Storage.getString(
							getApplicationContext(), username);
					if (localCard.length() != 0) {
						cardNum.setText(localCard);
					}

				}
			}
		};
		showLoadingProgress();

		String path = Config.URL_GET_CARDS;
		Map<String, String> map = new HashMap<String, String>();
		// 默认是第一页，每页20条，这里没有传参数，最多取20条
		// 如果需要传参数，可以使用Util.httpRequestToGetWithParams(url, l, el, map)
		map.put("pageNo", "1");
		map.put("pageSize", "20");
		Util.httpRequestToGetWithParams(path, sListener, this, map);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.additive:
			AddNumber();
			break;
		case R.id.subtraction:
			SubNumber();
			break;
		case R.id.month_number:
			// 暂时不让多月充值
			// if (mPopupWindow != null && mPopupWindow.isShowing()) {
			// mPopupWindow.dismiss();
			// return;
			// } else {
			// initmPopupWindowView();
			// mPopupWindow.showAsDropDown(v, 0, 0);
			// }
			break;
		case R.id.go_recharge:
			goToRechager();
			// goRechargeDirect();
			break;
		case R.id.go_recharge_two:
			goToRechager();
//			getDiscount();
			break;
		case R.id.title_left:
			finishActivityOut();
			break;
		case R.id.agree_it:
			isBoolean = !isBoolean;
			findViewById(R.id.ischecked).setVisibility(
					isBoolean ? View.VISIBLE : View.GONE);
			findViewById(R.id.go_recharge_two).setBackgroundResource(
					isBoolean ? R.drawable.btn_on : R.drawable.btn_off);
			findViewById(R.id.go_recharge_two).setEnabled(isBoolean);
			break;
		case R.id.lay_agree:
			Intent intentToAgree = new Intent(this,
					BacAgreementWebActivity.class);
			intentToAgree.putExtra("urltype", "agree");
			startActivityIn(intentToAgree);
			break;
		case R.id.toleft:
			if (mCardNameString.size() == 0) {
				return;
			}
			mCurrentCard--;
			if (mCurrentCard < 0) {
				mCurrentCard = 0;
				showToast("已经是第一张卡了");
				return;
			}
			if (mCardNameString.size() > mCurrentCard) {
				cardNum.setText(mCardNameString.get(mCurrentCard));
				cardNum.setSelection(mCardNameString.get(mCurrentCard).length());
			}

			break;
		case R.id.toright:
			if (mCardNameString.size() == 0) {
				return;
			}
			mCurrentCard++;
			if (mCurrentCard > mCardNameString.size() - 1) {
				mCurrentCard = mCardNameString.size() - 1;
				showToast("已经是最后一张卡了");
				return;
			}
			cardNum.setText(mCardNameString.get(mCurrentCard));
			cardNum.setSelection(mCardNameString.get(mCurrentCard).length());
			break;
		default:
			break;
		}

	}

	private void goRechargeCoupon() {
		Intent intentToBuyCoupon = new Intent(this, BuyCouponActivity.class);
		startActivityIn(intentToBuyCoupon);
	}

	/**
	 * 如果只选一个月，就进油卡直充
	 */
	private void goRechargeDirect() {
		Intent intentToRecharge = new Intent(this, RechargeActivity.class);
		startActivityIn(intentToRecharge);
	}

	private void goToRechager() {
		String cardString = cardNum.getText().toString().trim();
		if (cardString.length() == 0) {
			showToast("请输入卡号");
			return;
		}
		if (money_text.getText().toString().length() == 0) {
			showAlertDialog("提示", "请输入金额");
			return;
		}

		if (Integer.parseInt(money_text.getText().toString()) > 10000) {
			showAlertDialog("提示", "充值金额不能超过10000元");
			return;
		}

		getDiscount();
	}

	// 通过下拉框选择充值月数
	private void initmPopupWindowView() {
		View customView = getLayoutInflater().inflate(R.layout.choosenumber,
				null);
		mPopupWindow = new PopupWindow(customView, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		mPopupWindow.setFocusable(true);
		customView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mPopupWindow != null && mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
					mPopupWindow = null;
				}
				return false;
			}
		});
		TextView textView1 = (TextView) customView
				.findViewById(R.id.number_tv01);
		final String tv01 = textView1.getText().toString();
		textView1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				monthNum.setText(tv01);
				initPay(1);
				mPopupWindow.dismiss();
			}
		});
		TextView textView2 = (TextView) customView
				.findViewById(R.id.number_tv02);
		final String tv02 = textView2.getText().toString();
		textView2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				monthNum.setText(tv02);
				initPay(2);
				mPopupWindow.dismiss();
			}
		});
		TextView textView3 = (TextView) customView
				.findViewById(R.id.number_tv03);
		final String tv03 = textView3.getText().toString();
		textView3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				monthNum.setText(tv03);
				initPay(3);
				mPopupWindow.dismiss();
			}
		});
		TextView textView4 = (TextView) customView
				.findViewById(R.id.number_tv04);
		final String tv04 = textView4.getText().toString();
		textView4.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				monthNum.setText(tv04);
				initPay(4);
				mPopupWindow.dismiss();
			}
		});
		TextView textView5 = (TextView) customView
				.findViewById(R.id.number_tv05);
		final String tv05 = textView5.getText().toString();
		textView5.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				monthNum.setText(tv05);
				initPay(5);
				mPopupWindow.dismiss();
			}
		});
		TextView textView6 = (TextView) customView
				.findViewById(R.id.number_tv06);
		final String tv06 = textView6.getText().toString();
		textView6.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				monthNum.setText(tv06);
				initPay(6);
				mPopupWindow.dismiss();
			}
		});

	}

	// 增加月充值金额
	private void AddNumber() {
		String moneyString = money_text.getText().toString();
		if (moneyString.length() == 0) {
			moneyString = "0";
		}
		String discount = discountTextView.getText().toString();
		int num = Integer.parseInt(moneyString);
		int dis = Integer.parseInt(discount);
		int i = Integer.parseInt(monthNum.getText().toString());
		int offer = 100;
		if (num >= 10000) {
			showAlertDialog("提示", "充值金额不能超过10000元");
			return;
		}
		num += offer;
		int pay = num * i * dis / 100;
		money_text.setText(num + "");
		totalTextView.setText(num * i + "");
		ensurepayteTextView.setText(pay + "");

		if (!mIsRecharge) {
			initPay(Integer.parseInt(monthNum.getText().toString()));
		}

	}

	// 减少月充值金额
	private void SubNumber() {
		String moneyString = money_text.getText().toString();
		if (moneyString.length() == 0) {
			moneyString = "100";
		}
		String discount = discountTextView.getText().toString();
		int num = Integer.parseInt(moneyString);
		int dis = Integer.parseInt(discount);
		int i = Integer.parseInt(monthNum.getText().toString());
		if (num > 100) {
			num -= 100;
			int pay = num * i * dis / 100;
			money_text.setText(num + "");
			totalTextView.setText(num * i + "");
			ensurepayteTextView.setText(pay + "");
		} else {
//			num = 100;
			money_text.setText(num + "");
			totalTextView.setText(num + "");
			ensurepayteTextView.setText(num + "");
		}

		if (!mIsRecharge) {
			initPay(Integer.parseInt(monthNum.getText().toString()));
		}

	}

	// 选择月数后改变金额
	private void initPay(int i) {
		if (i > 1) {
			mIsRecharge = false;
			// findViewById(R.id.lay_container1).setVisibility(View.GONE);
			// findViewById(R.id.lay_container2).setVisibility(View.VISIBLE);
		} else {
			mIsRecharge = true;
			// findViewById(R.id.lay_container1).setVisibility(View.VISIBLE);
			// findViewById(R.id.lay_container2).setVisibility(View.GONE);
		}

		String moneyString = money_text.getText().toString();
		((TextView) findViewById(R.id.rl_01_tv02)).setText(moneyString);
		((TextView) findViewById(R.id.rl_02_tv02)).setText("" + i);
		TextView discount2 = (TextView) findViewById(R.id.discount_tv02);
		String discount = discount2.getText().toString();
		int num1 = Integer.parseInt(moneyString);
		int num2 = Integer.parseInt(discount);
		((TextView) findViewById(R.id.rl_03_tv02)).setText("" + num1 * num2
				/ 100);
		((TextView) findViewById(R.id.rl_tv02)).setText(""
				+ (num1 * num2 / 100 * i + num1 * i));
		ensurepayteTextView2.setText("" + num1 * i);
	}

	public void getDiscount(){
		// 如果没有网络，就加载本地图片
				ErrorListener errorListener = new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						Log.i(getClass().getName(), "error");
						dismissLoadingProgress();
						showToast("请检查网络后重试");
					}
				};
		
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("KeyToOilActivity----getdiscount", response.toString());
				HashMap<String, String> result = new Gson().fromJson(response
						.toString().trim(),
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				if (result != null && result.containsKey("totalRecharge")) {

					BigDecimal bd1 = new BigDecimal(result.get("totalRecharge"));
					BigDecimal bd2 = new BigDecimal(result.get("actualPayment"));
					BigDecimal dicount = bd1.subtract(bd2);

					if (dicount.compareTo(BigDecimal.ZERO) == 0) {
						String kahao = cardNum.getText().toString();
						String jine = money_text.getText().toString();
						String yueshu = monthNum.getText().toString();
						Intent intentToConfirm = new Intent(
								KeyToOilActivity.this, ConfirmRecharge.class);
						Bundle bundle = new Bundle();
						bundle.putString("cardNum", kahao);
						bundle.putString("money_text", jine);
						bundle.putString("monthNum", yueshu);
						bundle.putString("total", jine);
						Log.i("keytooil paymethod", "" + payMethod);
						bundle.putInt("paymethod", payMethod);
						intentToConfirm.putExtras(bundle);
						startActivityIn(intentToConfirm);
					} else {

						AlertDialog.Builder builder = new AlertDialog.Builder(
								KeyToOilActivity.this, R.style.Custom_dialog);
						final AlertDialog alertDialog = builder.create();
						alertDialog.setCanceledOnTouchOutside(false);
						alertDialog.show();
						Window window = alertDialog.getWindow();
						View view = LayoutInflater.from(KeyToOilActivity.this)
								.inflate(R.layout.dialog_alert, null);
						view.findViewById(R.id.ly_cancel).setVisibility(
								View.VISIBLE);
						view.findViewById(R.id.line)
								.setVisibility(View.VISIBLE);

						((TextView) (view.findViewById(R.id.tv_title)))
								.setText("提示");
						((TextView) (view.findViewById(R.id.tv_message)))
								.setText("本次充值优惠金额为" + dicount + "元");

						view.findViewById(R.id.ly_cancel).setOnClickListener(
								new OnClickListener() {
									@Override
									public void onClick(View v) {
										alertDialog.dismiss();
									}
								});

						view.findViewById(R.id.ly_ok).setOnClickListener(
								new OnClickListener() {
									@Override
									public void onClick(View v) {
										alertDialog.dismiss();
										String kahao = cardNum.getText()
												.toString();
										String jine = money_text.getText()
												.toString();
										String yueshu = monthNum.getText()
												.toString();
										Intent intentToConfirm = new Intent(
												KeyToOilActivity.this,
												ConfirmRecharge.class);
										Bundle bundle = new Bundle();
										bundle.putString("cardNum", kahao);
										bundle.putString("money_text", jine);
										bundle.putString("monthNum", yueshu);
										bundle.putString("total", jine);
										Log.i("keytooil paymethod", ""
												+ payMethod);
										bundle.putInt("paymethod", payMethod);
										intentToConfirm.putExtras(bundle);
										startActivityIn(intentToConfirm);
									}
								});
						window.setContentView(view);
						window.setLayout(
								(int) (Util.getWidth(getApplicationContext()) * 0.8),
								WindowManager.LayoutParams.WRAP_CONTENT);
					}
				}
			}
		
		};
		
		showLoadingProgress();
		String path = Config.URL_GET_DISCOUNT;
		Map<String, String> map = new HashMap<String, String>();
		map.put("amount", money_text.getText().toString());
		map.put("cardNo", cardNum.getText().toString());
		map.put("cycle", "1");
		map.put("transactionCode", "GAS001");
		Util.httpRequestToGetWithParams(path, sListener, errorListener, map);
	}
}
